import asyncio
import datetime

from redis import Redis
import redis
from user.models import User


class MyQueue:
    def __init__(self):
        self.r = Redis(decode_responses=True)
        self.r_len = self.r.hlen('nb')

        if not self.r_len == 0:
            self.r.hset('nb', '1', '1')
            self.r.hdel('nb', '1')
        self.__cs()

    def push(self, uid, level, username):
        self.r.hset('nb', '{}+{}+{}'.format(uid, level, datetime.datetime.now()), username)
        self.__cs()

    async def put(self, user_info):
        print(user_info['uid']+'开始')
        await asyncio.sleep(2)
        try:
            await User.objects.filter(id=user_info['uid']).update(username=user_info['username'])
        except Exception as e:
            self.r.rpush('result', user_info['uid'] + '_修改成功_' + user_info['username'])
            rs = '失败'
        else:
            self.r.rpush('result', user_info['uid'] + '_修改失败')
            rs = '成功'


        key = '{}+{}+{}'.format(user_info['uid'], user_info['level'], user_info['time'])
        self.r.hdel('nb', key)
        print(user_info['uid']+'结束')

    def pop(self):

        new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(new_loop)
        loop = asyncio.get_event_loop()
        tasks = [loop.create_task(self.put(i)) for i in self.queue]
        loop.run_until_complete(asyncio.wait(tasks))
        res = 'OK'

        return res


    def clean(self):
        self.r.delete('nb')

    def __cs(self):
        self.lis = []
        self.json = self.r.hgetall('nb')
        if len(self.json) == 0:
            return '无待执行队列'
        for i in self.json.items():
            li = i[0].split('+')
            # print(li)
            self.lis.append({
                'uid': li[0],
                'level': li[1],
                'time': li[2],
                'username': i[1]
            })
        level = []
        for i in range(len(self.lis)):
            lev = self.lis[i]['level']
            while len(level) < int(lev):
                level.append([])

            level[int(lev) - 1].append(self.lis[i])

        for i in range(len(level)):
            sorted(level[i], key=lambda i: i['time'], reverse=True)
        self.queue = []
        level = level[::-1]
        for i in level:
            self.queue.extend(i)

    def show(self):
        return self.queue

    def printf(self):
        for i in self.queue:
            print(i)


if __name__ == '__main__':
    sql = MyQueue()
    # sql.clean()
    # sql.push('15', 1, 'gao')
    # sql.show()
    # sql.printf()
    # print(sql.pop())

# import threading
# def Queue(value1=None,value2=None):
#     sql=MyQueue()
#     while 1:    #死循环
#         result=sql.pop()
#         if result=='OK':
#             break
#         print(result)
# # 启动多线程
# for index in range(3):
#     thread = threading.Thread(target=Queue)
#     thread.start()#执行



